<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Disruptor | 推推蛋</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
    <meta name="keywords" content="朱军函,大兄弟,chuck,BigBrother" />
  
  <meta name="description" content="DisruptorDisruptor是什么（http:&#x2F;&#x2F;ifeve.com&#x2F;disruptor） 1：Disruptor是英国外汇交易公司LMAX开发的一个高性能队列，研发的初衷是解决内存队列的延迟问题（在性能测试中发现竟然与I&#x2F;O操作处于同样的数量级） 2：Disruptor实现对了队列的功能并且是一个有界队列。可以用于生产者-消费者模型。 juc下的队列    队列 有界性 锁 数据结构">
<meta property="og:type" content="article">
<meta property="og:title" content="Disruptor">
<meta property="og:url" content="https://tuituidan.gitee.io/blog/2017/06/18/Disruptor/index.html">
<meta property="og:site_name" content="推推蛋">
<meta property="og:description" content="DisruptorDisruptor是什么（http:&#x2F;&#x2F;ifeve.com&#x2F;disruptor） 1：Disruptor是英国外汇交易公司LMAX开发的一个高性能队列，研发的初衷是解决内存队列的延迟问题（在性能测试中发现竟然与I&#x2F;O操作处于同样的数量级） 2：Disruptor实现对了队列的功能并且是一个有界队列。可以用于生产者-消费者模型。 juc下的队列    队列 有界性 锁 数据结构">
<meta property="og:locale" content="zh">
<meta property="article:published_time" content="2017-06-17T16:00:00.000Z">
<meta property="article:modified_time" content="2019-05-09T11:09:11.900Z">
<meta property="article:author" content="推推蛋">
<meta property="article:tag" content="Disruptor">
<meta property="article:tag" content="RingBuffer">
<meta name="twitter:card" content="summary">
  
  
    <link rel="icon" href="/favicon.ico">
  
  <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>

  

  
  

<meta name="generator" content="Hexo 4.2.1"></head>

<body>
  <div id="container">
      <header id="header">
    <div id="banner"></div>
    <div id="header-outer">
        <div id="header-menu" class="header-menu-pos animated">
            <div class="header-menu-container">
                <a href="/" class="left">
                    <span class="site-title">zhujunhan&#39;s Blog</span>
                </a>
                <nav id="header-menu-nav" class="right">
                    
                    <a  href="/">
                        <i class="fa fa-home"></i>
                        <span>首页</span>
                    </a>
                    
                    <a  href="/archives">
                        <i class="fa fa-archive"></i>
                        <span>归档</span>
                    </a>
                    
                    <a  href="/about">
                        <i class="fa fa-user"></i>
                        <span>关于</span>
                    </a>
                    
                </nav>
                <a class="mobile-header-menu-button">
                    <i class="fa fa-bars"></i>
                </a>
            </div>
        </div>
        <div id="header-row">
            <div id="logo">
                <a href="/">
                    <img src="/images/logo.jpg" alt="logo">
                </a>
            </div>
            <div class="header-info">
                <div id="header-title">
                    
                    <h2>
                        0 error 0 warning
                    </h2>
                    
                </div>
                <div id="header-description">
                    
                    <h3>
                        talk is cheap,show me the code
                    </h3>
                    
                </div>
            </div>
            <nav class="header-nav">
                <div class="social">
                    
                        <a title="home" target="_blank" href="//zhujunhan.github.io">
                            <i class="fa fa-home fa-2x"></i></a>
                    
                        <a title="github" target="_blank" href="//github.com/zhujunhan">
                            <i class="fa fa-github fa-2x"></i></a>
                    
                </div>
            </nav>
        </div>
    </div>
</header>
      <div class="outer">
        <section id="main" class="body-wrap"><article id="post-Disruptor" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-inner">
    
      <header class="article-header">
        
  
    <h1 class="post-title" itemprop="name">
      Disruptor
    </h1>
    <div class="post-title-bar">
      <ul>
          
              <li>
                  <i class="fa fa-book"></i>
                  
                      <a href="/categories/Disruptor/">Disruptor</a>
                  
              </li>
          
        <li>
          <i class="fa fa-calendar"></i>  2017-06-18
        </li>
        <li>
          <i class="fa fa-eye"></i>
          <span id="busuanzi_value_page_pv"></span>
        </li>
      </ul>
    </div>
  

          
      </header>
    
    <div class="article-entry post-content" itemprop="articleBody">
      
            
            <h1 id="Disruptor"><a href="#Disruptor" class="headerlink" title="Disruptor"></a>Disruptor</h1><p><strong>Disruptor是什么</strong>（<a href="http://ifeve.com/disruptor）" target="_blank" rel="noopener">http://ifeve.com/disruptor）</a></p>
<p>1：Disruptor是英国外汇交易公司LMAX开发的一个高性能队列，研发的初衷是解决内存队列的延迟问题（在性能测试中发现竟然与I/O操作处于同样的数量级）</p>
<p>2：Disruptor实现对了队列的功能并且是一个有界队列。可以用于生产者-消费者模型。</p>
<p><strong>juc下的队列</strong></p>
<table>
<thead>
<tr>
<th>队列</th>
<th>有界性</th>
<th>锁</th>
<th>数据结构</th>
</tr>
</thead>
<tbody><tr>
<td>ArrayBlockingQueue</td>
<td>bounded</td>
<td>加锁</td>
<td>arraylist</td>
</tr>
<tr>
<td>LinkedBlockingQueue</td>
<td>optionally-bounded</td>
<td>加锁</td>
<td>linkedlist</td>
</tr>
<tr>
<td>ConcurrentLinkedQueue</td>
<td>unbounded</td>
<td>无锁</td>
<td>linkedlist</td>
</tr>
<tr>
<td>LinkedTransferQueue</td>
<td>unbounded</td>
<td>无锁</td>
<td>linkedlist</td>
</tr>
<tr>
<td>PriorityBlockingQueue</td>
<td>unbounded</td>
<td>加锁</td>
<td>heap</td>
</tr>
<tr>
<td>DelayQueue</td>
<td>unbounded</td>
<td>加锁</td>
<td>heap</td>
</tr>
</tbody></table>
<p>1：从上图可以看出，juc下的队列基本采用加锁方式保证线程安全。通过不加锁的方式实现的队列都是无界的（无法保证队列的长度在限定的范围）。而加锁的方式可以实现有界队列。在稳定性要求特别高的系统中，为了防止生产者速度过快，导致内存溢出，只能选择有界队列。</p>
<p>2：加锁的方式通常严重影响性能。线程会因为竞争不到锁而被挂起，等锁被释放的时候，线程又会被恢复，这个过程中存在着很大的开销，并且通常会有较长时间的中断，因为当一个线程正在等待锁时，它不能做任何其他事情。如果一个线程在持有锁的情况下被延迟执行，例如发生了缺页错误、调度延迟或者其它类似情况，那么所有需要这个锁的线程都无法执行下去。如果被阻塞线程的优先级较高，而持有锁的线程优先级较低，就会发生优先级反转。</p>
<p>3：有界队列通常采用数组实现。但是采用数组实现又会引发另外一个问题false sharing(伪共享)。</p>
<p><strong>Disruptor核心类</strong></p>
<p>1：RingBuffer：Disruptor最主要的组件，仅仅负责存储和更新事件对象。</p>
<p>2：Sequence：Disruptor使用Sequence来表示一个特殊组件处理的序号。和Disruptor一样，每一个消费者（EventProcessor）都维持着一个Sequence。大部分的并发代码依赖这这个值。这个类维护了一个long类型的value，采用的unsafe进行的更新操作。</p>
<p>3：Sequencer：这是Disruptor真正的核心。实现了这个接口的两种生产者（单生产者和多生产者）均实现了所有的并发算法，为了在生产者和消费者之间进行准确快速的数据传递。</p>
<p>4：SequenceBarrier：由Sequencer生成，并且包含了已经发布的Sequence的引用，这些Sequence源于Sequencer和一些独立的消费者的Sequence。它包含了决定是否有供消费者消费的Event的逻辑。用来权衡当消费者无法从RingBuffer里面获取事件时的处理策略。（例如：当生产者太慢，消费者太快，会导致消费者获取不到新的事件会根据该策略进行处理，默认会堵塞）</p>
<p>5：WaitStrategy：决定一个消费者将如何等待生产者将Event置入Disruptor的策略。用来权衡当生产者无法将新的事件放进RingBuffer时的处理策略。（例如：当生产者太快，消费者太慢，会导致生产者获取不到新的事件槽来插入新事件，则会根据该策略进行处理，默认会堵塞）</p>
<p>6：Event：从生产者到消费者过程中所处理的数据单元。Disruptor中没有代码表示Event，因为它完全是由用户定义的。</p>
<p>7：EventProcessor：主要事件循环，处理Disruptor中的Event，并且拥有消费者的Sequence。它有一个实现类是BatchEventProcessor，包含了event loop有效的实现，并且将回调到一个EventHandler接口的实现对象。</p>
<p>8：EventHandler：由用户实现并且代表了Disruptor中的一个消费者的接口。</p>
<p>9：WorkHandler：在work模式下使用。由用户实现并且代表了Disruptor中的多个消费者的接口。</p>
<p>10：WorkProcessor：确保每个sequence只被一个processor消费，在同一个WorkPool中的处理多个WorkProcessor不会消费同样的sequence。</p>
<p>11：WorkerPool：一个WorkProcessor池，其中WorkProcessor将消费Sequence，所以任务可以在实现WorkHandler接口的worker之间移交</p>
<p>12：LifecycleAware：当BatchEventProcessor启动和停止时，实现这个接口用于接收通知。</p>
<p><strong>Disruptor为什么这么快</strong></p>
<p>1、不使用锁，通过内存屏障和原子性的CAS操作替换锁。</p>
<p>2、缓存基于数组而不是链表，用位运算替代求模%。缓存的长度总是2的n<br>次方，这样可以用位运算i &amp; (length -1)替代i % length。</p>
<p>3、去除伪共享，CPU的缓存一般是以缓存行为最小单位的，对应主存的<br>一块相应大小的单元，当前的缓存行大小一般是64字节，每个缓存行<br>—次只能被一个CPU核访问，如果一个缓存行被多个CPU核访问，就<br>会造成竞争，导致某个核必须等待其他核处理完了才能继续处理，影响<br>性能。去除伪共享就是确保CPU核访问某个缓存行时不会出现争用。</p>
<p>4、预分配缓存对象，通过更新缓存里对象的属性而不是删除对象来减少<br>垃圾回收。</p>

            <div class="post-copyright">
    <div class="content">
        <p>最后更新： 2019年05月09日 19:09</p>
        <p>原始链接： <a class="post-url" href="/2017/06/18/Disruptor/" title="Disruptor">https://tuituidan.gitee.io/blog/2017/06/18/Disruptor/</a></p>
        <footer>
            <a href="https://tuituidan.gitee.io/blog">
                <img src="/images/logo.jpg" alt="推推蛋">
                推推蛋
            </a>
        </footer>
    </div>
</div>

      
        
            
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;">赏</a>
</div>

<div id="reward" class="post-modal reward-lay">
    <a class="close" href="javascript:;" id="reward-close">×</a>
    <span class="reward-title">
        <i class="icon icon-quote-left"></i>
        有用就请我喝咖啡吧
        <i class="icon icon-quote-right"></i>
    </span>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/images/wechat_code.jpg" alt="打赏二维码">
        </div>
        <div class="reward-select">
            
            <label class="reward-select-item checked" data-id="wechat" data-wechat="/images/wechat_code.jpg">
                <img class="reward-select-item-wechat" src="/images/wechat.png" alt="微信">
            </label>
            
            
            <label class="reward-select-item" data-id="alipay" data-alipay="/images/alipay_code.jpg">
                <img class="reward-select-item-alipay" src="/images/alipay.png" alt="支付宝">
            </label>
            
        </div>
    </div>
</div>


        
    </div>
    <footer class="article-footer">
        
        
<div class="post-share">
    <a href="javascript:;" id="share-sub" class="post-share-fab">
        <i class="fa fa-share-alt"></i>
    </a>
    <div class="post-share-list" id="share-list">
        <ul class="share-icons">
          <li>
            <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://tuituidan.gitee.io/blog/2017/06/18/Disruptor/&title=《Disruptor》 — 推推蛋&pic=cover_picture/disruptor.png" data-title="微博">
              <i class="fa fa-weibo"></i>
            </a>
          </li>
          <li>
            <a class="weixin share-sns" id="wxFab" href="javascript:;" data-title="微信">
              <i class="fa fa-weixin"></i>
            </a>
          </li>
          <li>
            <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://tuituidan.gitee.io/blog/2017/06/18/Disruptor/&title=《Disruptor》 — 推推蛋&source=" data-title="QQ">
              <i class="fa fa-qq"></i>
            </a>
          </li>
          <li>
            <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://tuituidan.gitee.io/blog/2017/06/18/Disruptor/" data-title="Facebook">
              <i class="fa fa-facebook"></i>
            </a>
          </li>
          <li>
            <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《Disruptor》 — 推推蛋&url=https://tuituidan.gitee.io/blog/2017/06/18/Disruptor/&via=https://tuituidan.gitee.io/blog" data-title="Twitter">
              <i class="fa fa-twitter"></i>
            </a>
          </li>
          <li>
            <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://tuituidan.gitee.io/blog/2017/06/18/Disruptor/" data-title="Google+">
              <i class="fa fa-google-plus"></i>
            </a>
          </li>
        </ul>
     </div>
</div>
<div class="post-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;" id="wxShare-close">×</a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=https://tuituidan.gitee.io/blog/2017/06/18/Disruptor/" alt="微信分享二维码">
</div>

<div class="mask"></div>

        
        <ul class="article-footer-menu">
            
            
  <li class="article-footer-tags">
    <i class="fa fa-tags"></i>
      
    <a href="/tags/Disruptor/" class="color5">Disruptor</a>
      
    <a href="/tags/RingBuffer/" class="color1">RingBuffer</a>
      
  </li>

        </ul>
        
    </footer>
  </div>
</article>


    <aside class="post-toc-pos post-toc-top" id="post-toc">
        <nav class="post-toc-wrap">
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#Disruptor"><span class="post-toc-text">Disruptor</span></a></li></ol>
        </nav>
    </aside>
    

<nav id="article-nav">
  
    <a href="/2018/06/18/webuploader/" id="article-nav-newer" class="article-nav-link-wrap">

      <span class="article-nav-title">
        <i class="fa fa-hand-o-left" aria-hidden="true"></i>
        
          基于百度webuploader封装的上传控件
        
      </span>
    </a>
  
  
    <a href="/2017/06/18/SpringValidator/" id="article-nav-older" class="article-nav-link-wrap">
      <span class="article-nav-title">Disruptor</span>
      <i class="fa fa-hand-o-right" aria-hidden="true"></i>
    </a>
  
</nav>



    
        <link rel="stylesheet" href="//unpkg.com/gitment/style/default.css">
    <script src="//unpkg.com/gitment/dist/gitment.browser.js"></script>
    <div id="comments">
        <script>
            var gitment = new Gitment({
                owner: 'zhujunhan',
                repo: 'zhujunhan.github.io',
                oauth: {
                    client_id: 'c2c63d0ea4d9d2d02a69',
                    client_secret: '453c28c988d7d00d5b81d1b3f703295b809d5500',
                },
            })
            gitment.render('comments')
        </script>
    </div>

    
</section>
        
      </div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info" class="inner">
      
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


      <p>
        Copyright
      &copy; 2020 推推蛋<br>
      </p>
    </div>
  </div>
</footer>
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
  var mihoConfig = {
      root: "https://tuituidan.gitee.io/blog",
      animate: true,
      isHome: false,
      share: true,
      reward: 1
  }
</script>
<div class="sidebar">
    <div id="sidebar-search" title="Search">
        <i class="fa fa-search"></i>
    </div>
    <div id="sidebar-category" title="Categories">
        <i class="fa fa-book"></i>
    </div>
    <div id="sidebar-tag" title="Tags">
        <i class="fa fa-tags"></i>
    </div>
    <div id="sidebar-top">
        <span class="sidebar-top-icon"><i class="fa fa-angle-up"></i></span>
    </div>
</div>
<div class="sidebar-menu-box" id="sidebar-menu-box">
    <div class="sidebar-menu-box-container">
        <div id="sidebar-menu-box-categories">
            <a class="category-link" href="/categories/Disruptor/">Disruptor</a><a class="category-link" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a>
        </div>
        <div id="sidebar-menu-box-tags">
            <a href="/tags/Disruptor/" style="font-size: 20px;">Disruptor</a> <a href="/tags/RingBuffer/" style="font-size: 20px;">RingBuffer</a> <a href="/tags/webuploader/" style="font-size: 10px;">webuploader</a> <a href="/tags/%E5%89%8D%E7%AB%AF/" style="font-size: 10px;">前端</a>
        </div>
    </div>
    <a href="javascript:;" class="sidebar-menu-box-close">&times;</a>
</div>
<div class="mobile-header-menu-nav" id="mobile-header-menu-nav">
    <div class="mobile-header-menu-container">
        <span class="title">菜单</span>
        <ul class="mobile-header-menu-navbar">
            
            <li>
                <a  href="/">
                    <i class="fa fa-home"></i><span>首页</span>
                </a>
            </li>
            
            <li>
                <a  href="/archives">
                    <i class="fa fa-archive"></i><span>归档</span>
                </a>
            </li>
            
            <li>
                <a  href="/about">
                    <i class="fa fa-user"></i><span>关于</span>
                </a>
            </li>
            
        </ul>
    </div>
    <div class="mobile-header-tag-container">
        <span class="title">标签</span>
        <div id="mobile-header-container-tags">
            <a href="/tags/Disruptor/" style="font-size: 20px;">Disruptor</a> <a href="/tags/RingBuffer/" style="font-size: 20px;">RingBuffer</a> <a href="/tags/webuploader/" style="font-size: 10px;">webuploader</a> <a href="/tags/%E5%89%8D%E7%AB%AF/" style="font-size: 10px;">前端</a>
        </div>
    </div>
</div>
<div class="search-wrap">
    <span class="search-close">&times;</span>
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
            <i class="icon icon-lg icon-chevron-left"></i>
        </a>
        <input class="search-field" placeholder="搜索..." id="keywords">
        <a id="search-submit" href="javascript:;">
            <i class="fa fa-search"></i>
        </a>
    <div class="search-container" id="search-container">
        <ul class="search-result" id="search-result">
        </ul>
    </div>
</div>

<div id="search-tpl">
    <li class="search-result-item">
        <a href="{url}" class="search-item-li">
            <span class="search-item-li-title" title="{title}">{title}</span>
        </a>
    </li>
</div>

<script src="/js/search.js"></script>


<script src="/js/main.js"></script>









  
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.5.0/animate.min.css">

  <script src="//cdn.bootcss.com/scrollReveal.js/3.0.5/scrollreveal.js"></script>
  
<script src="/js/animate.js"></script>



  
<script src="/js/pop-img.js"></script>

  <script>
     $(".article-entry p img").popImg();
  </script>

  </div>
</body>
</html>